﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace CheckFreeWayServer
{
    class TrataConexaoSocketClient
    {
        private const int TAMANHO_HEADER = 10;
        
        private Socket _sck;
        private int _port;

        public TrataConexaoSocketClient(Socket sck, int port)
        {
            _sck = sck;
            _port = port;
        }

        public void Run()
        {
            String strBody = string.Empty;

            _sck.SendTimeout = 60000; // Milisegundos
            _sck.ReceiveTimeout = 60000;// Milisegundos

            try
            {
                // Recebe Header
                while (_sck.Available < TAMANHO_HEADER)
                    Thread.Sleep(1);

                byte[] bufferHeader = new byte[TAMANHO_HEADER];
                _sck.Receive(bufferHeader);

                MemoryStream msHeader = new MemoryStream(bufferHeader);
                StreamReader srHeader = new StreamReader(msHeader);
                String strHeader = srHeader.ReadToEnd();

                int tamanhoBody = Convert.ToInt32(strHeader);

                // Recebe Mensagem
                while (_sck.Available < tamanhoBody)
                    Thread.Sleep(1);

                byte[] bufferBody = new byte[tamanhoBody];
                _sck.Receive(bufferBody);

                MemoryStream msBody = new MemoryStream(bufferBody);
                StreamReader srBody = new StreamReader(msBody);
                strBody = srBody.ReadToEnd();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.StackTrace, System.Diagnostics.EventLogEntryType.Error, 7703);
                System.Diagnostics.EventLog.WriteEntry(ex.Source, "Erro ao receber mensagem na porta: " + _port.ToString(), System.Diagnostics.EventLogEntryType.Error, 7703);
            }

            try
            {

                // Monta Resposta
                strBody = strBody + " Received!";

                String msgResposta = "0000000000";
                msgResposta = msgResposta + strBody.Length.ToString();
                msgResposta = msgResposta.Substring(msgResposta.Length - TAMANHO_HEADER);

                msgResposta = msgResposta + strBody;

                // Envia Resposta
                byte[] bytResp = new byte[msgResposta.Length];

                MemoryStream msResp = new MemoryStream();
                StreamWriter sr = new StreamWriter(msResp);
                sr.Write(msgResposta);
                sr.Flush();
                System.Text.ASCIIEncoding enc = new ASCIIEncoding();
                bytResp = enc.GetBytes(msgResposta);

                _sck.SendBufferSize = msgResposta.Length;
                _sck.Send(bytResp);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.StackTrace, System.Diagnostics.EventLogEntryType.Error, 7704);
                System.Diagnostics.EventLog.WriteEntry(ex.Source, "Erro ao receber mensagem na porta: " + _port.ToString(), System.Diagnostics.EventLogEntryType.Error, 7704);
            }

            _sck.Disconnect(false);
            _sck.Close();
        }
    }
}
